'use strict';

define([
  'angular',
  'angularAMD'
], function(ng, angularAMD) {

  angularAMD.controller('periodListCtrl', ['$scope', '$http', '$location', 'ngDialog', '$filter',
    function($scope, $http, $location, ngDialog, $filter) {
      var searchObj = $location.search();

      $scope.selection={
        "tab": searchObj.status ? searchObj.status : '全部'
      }

      $scope.switchTab = function(status){
        $scope.selection.tab = status;
      }

      updatePeriods()
		
      function updatePeriods(){
        $http.get("index.php?route=rest/period/periods").then(
            function(result) {
              if (result.data.success) {
                $scope.periodList = result.data.data.periods;
                if($scope.periodList){
                  var periodArr = [];
                  for(var key in $scope.periodList){
                    angular.forEach($scope.periodList[key],function(periodItem){
					  var month = parseInt($filter("date")(periodItem["date_added"],"M"));
					  var year = parseInt($filter("date")(periodItem["date_added"],"yyyy"))
					  var datetemp = month+1;

					  if(year<2018 && month<6)
				      {
						  $datetemp = 7;
					  }

					  var paydate = $filter("date")(periodItem["date_added"],"yyyy")+"-"+datetemp+"-20";
					  periodItem["pay_date"] = paydate;
                      periodArr.push(periodItem);
                    })
                  }
                  $scope.periodList['全部'] = sortPeriodList(periodArr);
                }
              }
            }
        )
      }

      $scope.gotoOrder = function(order_id){
        $location.url("/order/"+order_id);
      }


      $scope.confirmReceived = function(period_id){
        ngDialog.openConfirm({
          template: 'confirmReceivedDialog.html',
          className: 'ngdialog-theme-default'
        }).then(function(value) {
          $http.get('index.php?route=feed/rest_api/confirmShipment&period_id='+period_id)
          .then(function(result) {
             updatePeriods()
          })
        }, function(value) {
          console.log('cancel')
        });
      }

      $scope.showAllPayments = function(){
        $scope.show_all_payment = true;
      }

      $scope.goToFastpay = function(period_id,payment_code){
        var submitData = {};
        submitData.period_id = period_id;
        submitData.payment_code = payment_code;
        $http.post('index.php?route=rest/simple_checkout/fastpay', submitData)
          .then(function(result) {
            if (result.data && result.data.success) {
              if(result.data.data.is_cod){
                $location.path('/rest/cart');
              }else{
                $location.path('/payment/card');                
              }

            } else {
              $('body').html(result.data);
            }
          }) 
      }

      $scope.gotoLuckydraw = function(period){
        if(period.luckydraw.left_times>0) {
          var period_id = period.period_id;
          var luckydraw_id = period.luckydraw.luckydraw_id
          $location.url("/period/"+period_id+"/luckydraw/"+luckydraw_id);  
        }
      }

      function sortPeriodList(array){
        var len=array.length,i,j,tmp;  
        for(i=len-1;i>=1;i--){  
          for(j=0;j<=i-1;j++){  
            if(array[j].period_id<array[j+1].period_id){  
              var d=array[j+1];  
              array[j+1]=array[j];  
              array[j]=d;  
            }  
          }
        }  
        return array;  
      }
    }
  ]);

  angularAMD.controller('periodCtrl', ['$scope', '$routeParams', '$http', '$location', 'ngDialog',
    function($scope, $routeParams, $http, $location, ngDialog) {
      var periodId = $routeParams.period_id;
      if(!periodId){
        alert("缺少账期id..");return;
      }
      
      function getPeriodInfo(){
        $http.get("index.php?route=rest/period/periods&id="+periodId).then(
            function(result) {
              if (result.data.success) {
                $scope.periodInfo = result.data.data;
              }
            }
        )
      }

      $scope.printBill = function(){
        if($scope.periodInfo.bill_status == 0){
          ngDialog.openConfirm({
            template: 'confirmPrintDialog.html',
            className: 'ngdialog-theme-default'
          }).then(function(value) {
            $http.post('index.php?route=rest/account/saveIs_invoice&period_id='+$scope.periodInfo.period_id, {
              is_invoice_id: 1
            }).then(function(result) {
              if (result.data && result.data.success) {
                getPeriodInfo();
              }
            })
          }, function(value) {
            console.log('cancel')
          });
        }
      }

      $scope.gotoReview = function(period_id,period_product_id){
        $location.url("period/"+period_id+"/review/"+period_product_id);
      }

      getPeriodInfo();

    }
  ]);

  angularAMD.controller('reviewCtrl', ['$scope', '$routeParams', '$http', '$location',
    function($scope, $routeParams, $http, $location) {
      var periodId = $routeParams.period_id;
      var periodProductId = $routeParams.period_product_id;
      if(!periodId){
        alert("缺少账期id..");return;
      }

      $scope.review = {
        rating:5,
        is_anony:false
      };
      
      $http.get("index.php?route=rest/period/periods&id="+periodId).then(
          function(result) {
            if (result.data.success) {
              $scope.periodInfo = result.data.data;
              if($scope.periodInfo.products){
                for(var i=0;i<$scope.periodInfo.products.length;i++){
                  if($scope.periodInfo.products[i].period_product_id == periodProductId){
                    $scope.product = $scope.periodInfo.products[i];
                    break;
                  }
                }
              }
            }
          }
      )

      $scope.gotoReview = function(){
        if(!$scope.review.text){
          BHZ.MessageDialog.show("请输入评价内容","知道了");
          return;
        }
        if($scope.review.text.length<0 || $scope.review.text.length>999){
          BHZ.MessageDialog.show("评价内容长度为1~1000个字符","知道了");
          return;
        }
        if(!$scope.review.rating){
          BHZ.MessageDialog.show("请选择评分","知道了");
          return;
        }
        var params = {
          text:$scope.review.text,
          rating:$scope.review.rating,
          is_anony:$scope.review.is_anony ? 1 : 0,
          period_product_id:$scope.product.period_product_id
        }
        $http.post("index.php?route=feed/rest_api/reviews&id="+$scope.product.product_id,params).then(
          function(result) {
            if (result.data.success) {
              BHZ.MessageBox.show("评价成功,即将自动跳转到订单详情页");
              setTimeout(function(){
                $location.path("/period/"+$scope.periodInfo.period_id);
                $scope.$apply();
              },1000)
            }
          }
        )
      }
    }
  ]);

  angularAMD.controller('periodLuckydrawCtrl', ['$scope', '$routeParams', '$http', '$location',
    function($scope, $routeParams, $http, $location) {
      var periodId = $routeParams.period_id;
      var luckydrawId = $routeParams.luckydraw_id;
      var turnplate={
          restaraunts:[],       //大转盘奖品名称
          colors:[],          //大转盘奖品区块对应背景颜色
          outsideRadius:192,      //大转盘外圆的半径
          textRadius:155,       //大转盘奖品位置距离圆心的距离
          insideRadius:68,      //大转盘内圆的半径
          startAngle:0,       //开始角度
          
          bRotate:false       //false:停止;ture:旋转
      };
      $scope.hit_price = '';

      $http.get("index.php?route=rest/period/getLuckydraw&id="+periodId).then(
          function(result) {
            if (result.data.success) {
              $scope.luckydraw = result.data.luckydraw;
              turnplate.restaraunts = ['谢谢参与'];
              turnplate.colors = ['#FFF4D6'];
              var idx = false;
              var color = '#FFF4D6';
              angular.forEach($scope.luckydraw.products, function(product){
                turnplate.restaraunts.push(product.price_name+' '+product.product_name);
                color = idx?"#FFF4D6":"#FFFFFF";
                idx = !idx;
                turnplate.colors.push(color);
              });
              $scope.drawRouletteWheel();
            }
          }
      )

      $('body,html').animate({
            scrollTop: 0
          }, 'fast');

      $scope.rotateTimeOut = function (){
        $('#wheelcanvas').rotate({
          angle:0,
          animateTo:2160,
          duration:8000,
          callback:function (){
            alert('网络超时，请检查您的网络设置！');
          }
        });
      };

      //旋转转盘 item:奖品位置; txt：提示语;
      $scope.rotateFn = function (item, left_times, txt){
        var angles = item * (360 / turnplate.restaraunts.length) - (360 / (turnplate.restaraunts.length*2));
        if(angles<270){
          angles = 270 - angles; 
        }else{
          angles = 360 - angles + 270;
        }
        $('#wheelcanvas').stopRotate();
        $('#wheelcanvas').rotate({
          angle:0,
          animateTo:angles+1800,
          duration:8000,
          callback:function (){
            if(item==1) {
              alert(txt);
            } else {
              $scope.hit_price = txt;
              $scope.$apply();
              alert('恭喜您抽中了' + txt + '！');
            }
            turnplate.bRotate = !turnplate.bRotate;
            if(left_times<=0) {
              $location.url("/periods");
              $scope.$apply();
            }
          }
        });
      };

      $scope.drawRouletteWheel = function () {   
        var canvas = document.getElementById("wheelcanvas");    
        if (canvas.getContext) {
          //根据奖品个数计算圆周角度
          var arc = Math.PI / (turnplate.restaraunts.length/2);
          var ctx = canvas.getContext("2d");
          //在给定矩形内清空一个矩形
          ctx.clearRect(0,0,422,422);
          //strokeStyle 属性设置或返回用于笔触的颜色、渐变或模式  
          ctx.strokeStyle = "#FFBE04";
          //font 属性设置或返回画布上文本内容的当前字体属性
          ctx.font = '16px Microsoft YaHei';      
          for(var i = 0; i < turnplate.restaraunts.length; i++) {       
            var angle = turnplate.startAngle + i * arc;
            ctx.fillStyle = turnplate.colors[i];
            ctx.beginPath();
            //arc(x,y,r,起始角,结束角,绘制方向) 方法创建弧/曲线（用于创建圆或部分圆）    
            ctx.arc(211, 211, turnplate.outsideRadius, angle, angle + arc, false);    
            ctx.arc(211, 211, turnplate.insideRadius, angle + arc, angle, true);
            ctx.stroke();  
            ctx.fill();
            //锁画布(为了保存之前的画布状态)
            ctx.save();   
            
            //----绘制奖品开始----
            ctx.fillStyle = "#E5302F";
            var text = turnplate.restaraunts[i];
            var line_height = 17;
            //translate方法重新映射画布上的 (0,0) 位置
            ctx.translate(211 + Math.cos(angle + arc / 2) * turnplate.textRadius, 211 + Math.sin(angle + arc / 2) * turnplate.textRadius);
            
            //rotate方法旋转当前的绘图
            ctx.rotate(angle + arc / 2 + Math.PI / 2);
            
            /** 下面代码根据奖品类型、奖品名称长度渲染不同效果，如字体、颜色、图片效果。(具体根据实际情况改变) **/
            if(text.indexOf(" ")>0){//流量包
              var texts = text.split(" ");
              for(var j = 0; j<texts.length; j++){
                ctx.font = j == 0?'bold 20px Microsoft YaHei':'16px Microsoft YaHei';
                if(j == 0){
                  ctx.fillText(texts[j]+" ", -ctx.measureText(texts[j]+" ").width / 2, j * line_height);
                }else{
                  ctx.fillText(texts[j], -ctx.measureText(texts[j]).width / 2, j * line_height);
                }
              }
            }else if(text.indexOf(" ") == -1 && text.length>6){//奖品名称长度超过一定范围 
              text = text.substring(0,6)+"||"+text.substring(6);
              var texts = text.split("||");
              for(var j = 0; j<texts.length; j++){
                ctx.fillText(texts[j], -ctx.measureText(texts[j]).width / 2, j * line_height);
              }
            }else{
              //在画布上绘制填色的文本。文本的默认颜色是黑色
              //measureText()方法返回包含一个对象，该对象包含以像素计的指定字体宽度
              ctx.fillText(text, -ctx.measureText(text).width / 2, 0);
            }
            
            //添加对应图标
            // if(text.indexOf("闪币")>0){
            //   var img= document.getElementById("shan-img");
            //   img.onload=function(){  
            //     ctx.drawImage(img,-15,10);      
            //   }; 
            //   ctx.drawImage(img,-15,10);  
            // }else if(text.indexOf("谢谢参与")>=0){
            //   var img= document.getElementById("sorry-img");
            //   img.onload=function(){  
            //     ctx.drawImage(img,-15,10);      
            //   };  
            //   ctx.drawImage(img,-15,10);  
            // }
            //把当前画布返回（调整）到上一个save()状态之前 
            ctx.restore();
            //----绘制奖品结束----
          }     
        } 
      }

      $('.pointer').click(function (){
        if($scope.luckydraw.left_times<=0) {
          alert('您的抽奖机会已用完');
          return;
        }
        if(turnplate.bRotate)return;
        turnplate.bRotate = !turnplate.bRotate;

        $http.get("index.php?route=rest/period/tryLuck&id="+periodId).then(
          function(result) {
            if (result.data.success) {
              $scope.luckydraw = result.data.luckydraw;
              var item = result.data.luckydraw.item;
              var left_times = result.data.luckydraw.left_times;
              $scope.rotateFn(item+1, left_times, turnplate.restaraunts[item]);
            }
          }
        )
        //获取随机数(奖品个数范围内)
        //奖品数量等于10,指针落在对应奖品区域的中心角度[252, 216, 180, 144, 108, 72, 36, 360, 324, 288]
      });
    }
  ]);

});
